package hu.bme.mit.rifl.business.nodes;

import hu.bme.mit.rifl.business.base.RiflOrderQueue;
import hu.bme.mit.rifl.business.base.WFElement;

/**
 * Worker node which books the transaction if the repository test returns an
 * "FEASIBLE" state. This step if performed simultaneously with the ServeOrder
 * step.
 */
public class BookTransaction extends WFElement {

	private static final int RIFL_BOOK2SERVE = 0;
	private static final int RIFL_SUCCESS2FULFILL = 1;

	/**
	 * Default constructor of the node. Sets the name (displayed on the GUI),
	 * the input queue(s) and the output queue(s).
	 */
	public BookTransaction() {
		super("BookTransaction");

		inputs.add(new RiflOrderQueue("rifl.check2success"));
		inputs.add(new RiflOrderQueue("rifl.serve2book"));
		outputs.add(RIFL_BOOK2SERVE, new RiflOrderQueue("rifl.book2serve"));
		outputs.add(RIFL_SUCCESS2FULFILL, new RiflOrderQueue(
				"rifl.success2fulfill"));
	}

	public static void main(String[] args) {
		BookTransaction node = new BookTransaction();
		node.run();
	}

	/**
	 * Business logic.
	 */
	@Override
	public void process() {
		this.order.setBooked(true);
		this.order.setStateCodes(6);
	}

	/**
	 * The overridden log result, since not the Order.state property is changed
	 * here, but the Order.isBooked.
	 */
	@Override
	protected void LogResult() {
		String log = this.getClass().getSimpleName() + ":Order with ID "
				+ this.order.getOrderID() + " BOOKED.";

		System.out.println(log);
		gui.log(log);
	}

	/**
	 * The output queue is selected with respect to the parallel node of the
	 * workflow, i.e. it's sent to the fulfill queue if it was processed by both
	 * nodes and sent to the another node is it wasn't.
	 */
	@Override
	protected void finish() {
		if (this.order.getState().equalsIgnoreCase("GETTINGSERVED")) {
			outputs.get(RIFL_SUCCESS2FULFILL).put(this.order);
			this.order = null;
		} else {
			outputs.get(RIFL_BOOK2SERVE).put(this.order);
			this.order = null;
		}
	}
}
